#ifndef __UTILITY_H
#define __UTILITY_H

#include <sys/types.h>
#include <stdarg.h>
#include <stdlib.h>
#include "cdefs.h"


#define MAX_MESSAGE_SIZE 1024
#define SUCCESS 0
#define FAILED -1
#define STRING_ELN 128
#define CONTENT_LEN 512
#define NAME_LEN 64
#ifndef MAX_BUF_SIZE
#define MAX_BUF_SIZE 1024
#endif
#ifndef NAME_PASSWD_SESSION_LEN
#define NAME_PASSWD_SESSION_LEN NAME_LEN		//长度和数据库中的长度对应
#endif //!NAME_PASSWD_SESSION_LEN


#ifdef __cplusplus
extern "C"
{
#endif //!__cplusplus

int util_snprintf(char *buf, ssize_t buflen, const char *format, ...);
int util_vsnprintf(char *buf, ssize_t buflen, const char *format, va_list ap);

#define _EVENT_ERR_ABORT ((int)0xdeaddead)

/* Evaluates to the same boolean value as 'p', and hints to the compiler that
 * we expect this value to be false. */
#if defined(__GNUC__) && __GNUC__ >= 3         /* gcc 3.0 or later */
#define EVUTIL_UNLIKELY(p) __builtin_expect(!!(p),0)
#else
#define EVUTIL_UNLIKELY(p) (p)
#endif

/* Replacement for assert() that calls event_errx on failure. */
#ifdef NDEBUG
#define UTIL_ASSERT(cond) _EVUTIL_NIL_CONDITION(cond)
#define UTIL_FAILURE_CHECK(cond) 0
#else
#define UTIL_ASSERT(cond)						\
	do {								\
		if (EVUTIL_UNLIKELY(!(cond))) {				\
			event_errx(_EVENT_ERR_ABORT,			\
			    "%s:%d: Assertion %s failed in %s",		\
			    __FILE__,__LINE__,#cond,__func__);		\
			/* In case a user-supplied handler tries to */	\
			/* return control to us, log and abort here. */	\
			(void)fprintf(stderr,				\
			    "%s:%d: Assertion %s failed in %s",		\
			    __FILE__,__LINE__,#cond,__func__);		\
			abort();					\
		}							\
	} while (0)
#define UTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
#endif



#if (!defined MAX) && (!defined MIN)
#define MAX(a, b) \
    ({ __typeof__ (a) _a = (a); \
    __typeof__ (b) _b = (b); \
    _a > _b ? _a : _b; })

#define MIN(a, b) \
    ({ __typeof__ (a) _a = (a); \
    __typeof__ (b) _b = (b); \
    _a < _b ? _a : _b; })
#endif  //!MAX MIN

#ifndef FCLOSE
#define FCLOSE(fp)      \
    do                  \
    {                   \
        if (fp != NULL) \
        {               \
            fclose(fp); \
            fp = NULL;  \
        }               \
    } while (0)
#endif  //!FCLOSE

#ifndef CLOSE
#define CLOSE(fd)      \
    do                 \
    {                  \
        if (fd != -1)  \
        {              \
            close(fd); \
            fd = -1;   \
        }              \
    } while (0)
#endif  //!CLOSE

#ifdef __cplusplus
}
#endif  //!__cplusplus
#endif  //!__UTILITY_H